﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ConsoleApplicationTest
{
    class Program
    {
        private const int porNum = 81;
        [STAThread]
        public static void Main(string[] args)
        {
            SocketClientTest();
        }

        public static void SocketClientTest()
        {
            bool done = false;
            IPAddress serverIP = IPAddress.Parse("192.168.6.147");
            TcpListener listener = new TcpListener(serverIP, porNum);
            listener.Start();
            Console.Write("正在侦听81端口...");
            Socket client = listener.AcceptSocket();
            Console.WriteLine("\n处理连接请求...");
            while (!done)
            {
                byte[] bytes = new byte[10240];
                int bytesRead = 0;
                string rStr = string.Empty ;
                
                while (rStr.IndexOf("\r\n") < 0)
                {
                    bytesRead = client.Receive(bytes);
                    rStr += Encoding.ASCII.GetString(bytes, 0, bytesRead);
                }
                byte[] byteTime = Encoding.ASCII.GetBytes(((IPEndPoint)client.RemoteEndPoint).Address.ToString() + "\r\n");
                if (rStr == "close\r\n")
                {
                    client.Close();
                    break;
                }
                else
                {
                    Console.WriteLine(rStr);
                    client.Send(byteTime);
                }
            }
            listener.Stop();
        }

        public static void TcpClientTest()
        {
            bool done = false;
            IPAddress serverIP = IPAddress.Parse("192.168.6.147");
            TcpListener listener = new TcpListener(serverIP, porNum);
            listener.Start();
            while (!done)
            {
                Console.Write("正在侦听81端口...");
                TcpClient client = listener.AcceptTcpClient();
                Console.WriteLine("\n处理连接请求...");
                NetworkStream ns = client.GetStream();
                byte[] bytes = new byte[10240];
                int bytesRead = ns.Read(bytes, 0, bytes.Length);
                Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytesRead));
                byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString() + "-");
                try
                {
                    ns.Write(byteTime, 0, byteTime.Length);
                    ns.Close();
                    client.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            listener.Stop();
        }

    }
}
